import {
	Entity,
	Column,
	PrimaryGeneratedColumn,
	CreateDateColumn,
	UpdateDateColumn,
	OneToMany,
} from "typeorm";
import { OrderItem } from "../../order/entities/order-item.entity";
import { DateTransformer } from "../../../common/transformers/date.transformer";
import { ProductSpec } from "./product-spec.entity";
import { ProductSku } from "./product-sku.entity";

@Entity("products")
export class Product {
	@PrimaryGeneratedColumn()
	id: number;

	@Column({ length: 100 })
	name: string;

	@Column({
		type: "enum",
		enum: ["数码", "食品", "服装", "家居"],
		default: "数码",
	})
	category: string;

	@Column()
	price: number;

	// 虚拟字段：实际库存数量 - 不再存储在数据库中，而是通过SKU计算
	stock: number;

	// 虚拟字段：可用库存数量 - 不再存储在数据库中，而是通过SKU计算
	availableStock: number;

	@Column({
		type: "enum",
		enum: ["在售", "已下架"],
		default: "在售",
	})
	status: string;

	@Column({ nullable: true })
	image: string;

	@Column({ type: "text", nullable: true })
	description: string;

	@CreateDateColumn({
		name: "created_at",
		type: "datetime",
		transformer: new DateTransformer(),
		nullable: false,
	})
	createdAt: Date;

	@UpdateDateColumn({
		name: "updated_at",
		type: "datetime",
		transformer: new DateTransformer(),
		nullable: false,
	})
	updatedAt: Date;

	// 关系
	@OneToMany(() => OrderItem, (orderItem) => orderItem.product)
	orderItems: OrderItem[];

	// 规格关联
	@OneToMany(() => ProductSpec, (spec) => spec.product)
	specs: ProductSpec[];

	// SKU关联
	@OneToMany(() => ProductSku, (sku) => sku.product)
	skus: ProductSku[];

	// 计算库存的方法
	calculateStock(): void {
		if (this.skus && this.skus.length > 0) {
			this.stock = this.skus.reduce((total, sku) => total + sku.stock, 0);
			this.availableStock = this.skus.reduce(
				(total, sku) => total + sku.availableStock,
				0
			);
		} else {
			this.stock = 0;
			this.availableStock = 0;
		}
	}
}
